package com.carhailing.coupons.scheduled;

import com.carhailing.coupons.constant.CouponsActiveConstant;
import com.carhailing.coupons.service.CouponScheduleService;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author: Gd
 * @package: com.carhailing.coupons.scheduled
 * @Project: Online_Taxi_Project
 * @Name: CouponsActiveScheduled
 * @Date: 2024-7-26 15:35
 */
@Log4j2
@Service
public class CouponsActiveScheduled {

   @Autowired
   private RedissonClient redissonClient;

   @Autowired
   private CouponScheduleService couponScheduleService;


    /**
     * 优惠券抢券活动 定时上架   开始抢券
     * 防止幂等性问题 --> 比如：重复发放优惠券造成优惠券超库存现象
     */
//    @Scheduled(cron = "*/10 * * * * ?")
    public void uploadCouponsActiveScheduled() {
        log.info("优惠券抢券活动 定时上架   开始抢券...");
        // 分布式锁
        RLock lock = redissonClient.getLock(CouponsActiveConstant.UPLOAD_LOCK);
        try {
            lock.lock(10, TimeUnit.SECONDS);
            // 商家最近参与优惠券抢券活动的优惠券信息
            couponScheduleService.uploadCouponsActiveScheduled();
        }catch (Exception e){
            log.error("优惠券抢券活动 定时上架   开始抢券 异常",e);
        }finally {
            // 当前是否有锁
            if(lock.isLocked()){
                // 该线程是否有锁
                if(lock.isHeldByCurrentThread()){
                    // 释放锁
                    lock.unlock();
                }
            }
        }


    }
}
